﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using iver.Entity;
using Newtonsoft.Json;
using DBEntity;
namespace iver.Controllers
{
    /// <summary>
    /// 后台信息接口
    /// </summary>
    public class InfoController : ApiController
    {

        /// <summary>
        /// 获取信息列表
        /// </summary>
        /// <param name="req"></param>
        /// <returns>jsonstr</returns>
        [HttpPost]
        public ResResult InfoList([FromBody]ReqListQuery req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            var list = (from u in db.apInfo
                        join ut in db.apInfoType on u.infoTypeId equals ut.id into temp1
                        from infoType in temp1.DefaultIfEmpty()
                        join uu in db.sysUser on u.createBy equals uu.id into temp2
                        from user in temp2.DefaultIfEmpty()
                        where
                        req.id == null ?
                        1 == 1 :
                        u.infoTypeId == req.id
                        orderby u.id descending
                        select new
                        {
                            u.id,
                            u.infoTypeId,
                            u.isEnable,
                            u.orderNum,
                            u.remark,
                            u.title,
                            u.titleSub,
                            u.createTime,
                            u.updateTime,
                            u.viewNum,
                            //u.body,
                            u.bodySub,
                            u.cover,
                            u.createBy,
                            infoType.infoTypeName,
                            user.userName,
                        });
            var arr = list.Skip(req.limit * (req.page - 1)).Take(req.limit);
            int count = list.Count();
            return new ResResult
            {
                success = true,
                result = new
                {
                    count,
                    arr,
                }
            };
        }
        /// <summary>
        /// 得到可用信息类型列表
        /// </summary>
        /// <returns>jsonstr</returns>
        [HttpPost]
        public ResResult InfoTypeList([FromBody]ReqList req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            var list = (from u in db.apInfoType
                        where u.isEnable == true
                        orderby u.orderNum descending
                        select u);
            var arr = list.Skip(req.limit * (req.page - 1)).Take(req.limit);
            int count = list.Count();
            return new ResResult
            {
                success = true,
                result = new
                {
                    count,
                    arr,
                }
            };
        }
        public class ReqInfoList : ReqList
        {
            public string infoTypeIds { get; set; }
            public Nullable<int> createBy { get; set; }
            public string title { get; set; }
            public string remark { get; set; }
            public Nullable<bool> isEnable { get; set; }
            public string sort { get; set; }
            public string betweenTime { get; set; }
        }
        /// <summary>
        /// 获取信息列查询
        /// </summary>
        /// <param name="req"></param>
        /// <returns>jsonstr</returns>
        [HttpPost]
        public ResResult InfoListByQuery([FromBody]ReqInfoList req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }

            iverDB db = new iverDB();
            string[] strs = { };
            if (req.infoTypeIds != null)
            {
                strs = req.infoTypeIds.Split(',');
            }
            DateTime? beginTime = null;
            DateTime? endTime = null;

            //DateTime? beginTime = null;
            //DateTime? endTime = null;
            if (req.betweenTime != null)
            {
                string[] temp = req.betweenTime.Split(',');
                DateTime bt = Convert.ToDateTime(temp[0]);
                DateTime et = Convert.ToDateTime(temp[1]);
                beginTime = new DateTime(bt.Year, bt.Month, bt.Day, 0, 0, 0);
                endTime = new DateTime(et.Year, et.Month, et.Day, 23, 59, 59);

            }
            var list = (from u in db.apInfo
                        join ut in db.apInfoType on u.infoTypeId equals ut.id into temp1
                        from infoType in temp1.DefaultIfEmpty()
                        join uu in db.sysUser on u.createBy equals uu.id into temp2
                        from user in temp2.DefaultIfEmpty()
                        where
                           (req.infoTypeIds == null ? 1 == 1 : strs.Contains(u.infoTypeId.ToString()))
                            && (req.createBy == null ? 1 == 1 : u.createBy == req.createBy)
                            && (req.title == null ? 1 == 1 : u.title.Contains(req.title))
                            && (req.remark == null ? 1 == 1 : u.remark.Contains(req.remark))
                            && (req.isEnable == null ? 1 == 1 : u.isEnable == req.isEnable)
                            && (req.betweenTime == null ? 1 == 1 : (u.createTime >= beginTime && u.createTime <= endTime))

                        select new
                        {
                            u.id,
                            u.infoTypeId,
                            u.isEnable,
                            u.orderNum,
                            u.remark,
                            u.title,
                            u.titleSub,
                            u.createTime,
                            u.updateTime,
                            u.viewNum,
                            //u.body,
                            u.bodySub,
                            u.cover,
                            u.createBy,
                            infoType.infoTypeName,
                            user.userName,
                            infoType.treeIds,
                        });
            switch (req.sort)
            {
                case "infoTypeId":
                    list = list.OrderByDescending(p => p.infoTypeId);
                    break;
                case "orderNum":
                    list = list.OrderByDescending(p => p.orderNum);
                    break;
                case "viewNum":
                    list = list.OrderByDescending(p => p.viewNum);
                    break;
                case "createTime":
                    list = list.OrderByDescending(p => p.createTime);
                    break;
                case "updateTime":
                    list = list.OrderByDescending(p => p.updateTime);
                    break;
                default:
                    list = list.OrderByDescending(p => p.id);
                    break;
            }
            var arr = list.Skip(req.limit * (req.page - 1)).Take(req.limit);
            int count = list.Count();
            return new ResResult
            {
                success = true,
                result = new
                {
                    count,
                    arr,
                }
            };
        }
        /// <summary>
        /// 获取信息对象
        /// </summary>
        /// <param name="req">对象ID</param>
        /// <returns>jsonstr</returns>
        [HttpPost]
        public ResResult Info([FromBody] ReqID<int> req)
        {
            if (req.id == 0)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                };
            }
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            apInfo info = db.apInfo.FirstOrDefault(u => u.id == req.id);
            if (info == null)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                };
            }
            return new ResResult
            {
                success = true,
                result = info,
            };
        }
        /// <summary>
        /// 添加信息
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult InfoAdd([FromBody]apInfo req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            DateTime now = DateTime.Now;
            //req.createTime = DateTime.Parse(Convert.ToDateTime(req.createTime).ToString("yyyy-MM-dd HH:mm:ss"));
            req.updateTime = now;
            req.createBy = authInfo.userId;
            iverDB db = new iverDB();
            db.apInfo.Add(req);
            db.SaveChanges();
            Help.Log(authInfo, req.id.ToString());
            //if (req.cover != null)
            //{
            //    if (req.cover != "")
            //    {
            //        //添加缩略图
            //        string OldPath = System.Web.HttpContext.Current.Server.MapPath(req.cover);
            //        string fileName = System.IO.Path.GetFileName(OldPath);
            //        string pathName = "/up/" + "thumb" + "/";
            //        string createDir = System.Web.HttpContext.Current.Server.MapPath("~" + pathName);
            //        if (!System.IO.Directory.Exists(createDir))
            //        {
            //            System.IO.Directory.CreateDirectory(createDir);
            //        }
            //        string NewPath = System.Web.HttpContext.Current.Server.MapPath(pathName + fileName);
            //        if (!System.IO.File.Exists(NewPath))
            //        {
            //            iver.Controllers.Help.MakeThumbnail(OldPath, NewPath, 300, 200, "W");
            //        }
            //    }
            //}
            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessAdd,
                result = new
                {
                    id = req.id,
                },
            };

        }

        /// <summary>
        /// 编辑信息
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult InfoEdit([FromBody]apInfo req)
        {
            //System.Threading.Thread.Sleep(3000);
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            apInfo model = db.apInfo.FirstOrDefault(u => u.id == req.id);
            if (model == null)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                };
            }
            model.infoTypeId = req.infoTypeId == null ? model.infoTypeId : req.infoTypeId;
            model.title = req.title == null ? model.title : req.title;
            model.titleSub = req.titleSub == null ? model.titleSub : req.titleSub;
            model.body = req.body == null ? model.body : req.body;
            model.bodySub = req.bodySub == null ? model.bodySub : req.bodySub;
            model.cover = req.cover == null ? model.cover : req.cover;
            model.viewNum = req.viewNum == null ? model.viewNum : req.viewNum;
            model.orderNum = req.orderNum == null ? model.orderNum : req.orderNum;
            model.createTime = req.createTime == null ? model.createTime : req.createTime;
            model.updateTime = DateTime.Now;
            model.isEnable = req.isEnable == null ? model.isEnable : req.isEnable;
            model.remark = req.remark == null ? model.remark : req.remark;
            int result = db.SaveChanges();
            Help.Log(authInfo, req.id.ToString());
            //if (model.cover != null)
            //{
            //    if (model.cover != "")
            //    {
            //        //添加缩略图
            //        string OldPath = System.Web.HttpContext.Current.Server.MapPath(model.cover);
            //        string fileName = System.IO.Path.GetFileName(OldPath);
            //        string pathName = "/up/" + "thumb" + "/";
            //        string createDir = System.Web.HttpContext.Current.Server.MapPath("~" + pathName);
            //        if (!System.IO.Directory.Exists(createDir))
            //        {
            //            System.IO.Directory.CreateDirectory(createDir);
            //        }
            //        string NewPath = System.Web.HttpContext.Current.Server.MapPath(pathName + fileName);
            //        if (!System.IO.File.Exists(NewPath))
            //        {
            //            iver.Controllers.Help.MakeThumbnail(OldPath, NewPath, 300, 200, "W");
            //        }
            //    }
            //}
            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessEdit,
                result = new
                {
                    changeCount = result,
                },
            };
        }
        /// <summary>
        /// 信息复制
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult InfoCopy([FromBody]apInfo req)
        {
            //System.Threading.Thread.Sleep(3000);
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            apInfo model = db.apInfo.FirstOrDefault(u => u.id == req.id);
            if (model == null)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                };
            }

            db.apInfo.Add(model);
            db.SaveChanges();
            int result = db.SaveChanges();
            Help.Log(authInfo, req.id.ToString());
          
            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessEdit,
                result = new
                {
                    changeCount = result,
                },
            };
        }
        public class ReqInfoMulti
        {
            public List<int> idList { get; set; }
            public Nullable<int> infoTypeId { get; set; }
        }
        /// <summary>
        /// 编辑信息
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult InfoEditMulti([FromBody]ReqInfoMulti req)
        {
            //System.Threading.Thread.Sleep(3000);
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();

            var list = from u in db.apInfo
                         where req.idList.Contains(u.id)
                         select u;

            foreach (var item in list)   //重新赋值
            {
                item.infoTypeId = req.infoTypeId;
            }
            int result = db.SaveChanges();
            Help.Log(authInfo, Newtonsoft.Json.JsonConvert.SerializeObject(req));
            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessEdit,
                result = new
                {
                    changeCount = result,
                },
            };
        }
        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="req">id数组</param>
        /// <returns></returns>
        [HttpPost]
        public ResResult InfoDel([FromBody]ReqID<List<int>> req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            var list = db.apInfo.Where(u => req.id.Contains(u.id));
            int delCount = list.Count();
            if (delCount == 0)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                };
            }
            db.apInfo.RemoveRange(list);
            db.SaveChanges();
            Help.Log(authInfo, Newtonsoft.Json.JsonConvert.SerializeObject(req.id));
            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessDel,
                result = new
                {
                    delCount,
                },
            };

        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResResult uploadfImg()
        {
            Entity.AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            return Help.uploadfile("infoImg", 3);
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResResult uploadFile()
        {
            Entity.AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            return Help.uploadfile("infoFile", 200);
        }
    }
}